package simulator;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.StringTokenizer;

/**
 * Factory for creating Robots with different configurations of sensors.
 */
public class RobotFactory {
	public static Robot getDefaultConfiguration(Environment env, Simulator sim) {
		Robot robot = new Robot(sim);
		// TODO place new servos and locs
		robot.addSensor(new BumpSensor(env, 5.0, 0.0)); // TODO use dual bump
														// sensor
		// CENTER RF
		// public RangeFinder(Environment e, double x, double y, double
		// range,angle
		robot.addSensor(new RangeFinder(env, 0, 0.0, 150, 0));
		// RIGHT RF, on Servo
		robot.addSensor(new RangeFinder(env, 0, 0, 150, 0));
		RangeFinder[] r = { robot.getRangeFinders()[robot.getRangeFinders().length - 1] };
		robot.addSensor(new Servo(env, r, 45));
		// Left RF, on Servo
		robot.addSensor(new RangeFinder(env, 0, 0, 150, 0));
		RangeFinder[] r1 = { robot.getRangeFinders()[robot.getRangeFinders().length - 1] };
		robot.addSensor(new Servo(env, r1, -45));

		/*
		 * robot.addSensor(new RangeFinder(env, 0.0, 0.0, 100, 45));
		 * robot.addSensor(new RangeFinder(env, 0.0, 0.0, 100, -45));
		 * robot.addSensor(new RangeFinder(env, 0.0, 0.0, 100, 180+45));
		 * robot.addSensor(new RangeFinder(env, 0.0, 0.0, 100, 180-45));
		 */
		robot.addSensor(new BeaconSensor(env, 0.0, 0.0));
		robot.addSensor(new Compass(env));
		// robot.setServo(new Servo(robot.getRangeFinders()));*/
		return robot;
	}

	/**
	 * Download configuration via URL
	 */
	public static Robot loadConfiguration(Environment env, URL url,
			Simulator sim) throws IOException {
		Robot robot = new Robot(sim);
		BufferedReader in = new BufferedReader(new InputStreamReader(
				(InputStream) url.getContent()));

		String line = "";
		while ((line = in.readLine()) != null) {
			StringTokenizer st = new StringTokenizer(line, " ");
			if (st.countTokens() > 1) {
				String type = st.nextToken();
				if (type.equals("BeaconSensor")) {
					robot.addSensor(new BumpSensor(env, Double.parseDouble(st
							.nextToken()), Double.parseDouble(st.nextToken())));
				}
				if (type.equals("TouchSensor")) {
					robot.addSensor(new BumpSensor(env, Double.parseDouble(st
							.nextToken()), Double.parseDouble(st.nextToken())));
				}
				if (type.equals("RangeFinder")) {
					robot.addSensor(new RangeFinder(env, Double.parseDouble(st
							.nextToken()), Double.parseDouble(st.nextToken()),
							Integer.parseInt(st.nextToken()), Integer
									.parseInt(st.nextToken())));
				}
			}
		}
		return robot;
	}

}